package com.jqr.school.controller;


import com.jqr.school.po.Permission;
import com.jqr.school.service.PermissionService;

import org.bouncycastle.math.raw.Mod;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jqr.school.po.Role;
import com.jqr.school.service.RoleService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuzongbo
 * @since 2022-01-04
 */
@Controller
@RequestMapping("/admin/role")
public class RoleController {
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	@GetMapping("/index")
	public String index(Model model) {
		
		QueryWrapper<Role> queryWrapper=new QueryWrapper<>();
		queryWrapper.select("id","role_name","status","description");
		
//		Page<Role> page=new Page<Role>();
//
//		roleService.page(page, queryWrapper);
//		model.addAttribute("page", page);

		QueryWrapper<Permission> queryWrapper1=new QueryWrapper<>();
		queryWrapper1.select("id","code");
		//权限
		List<Permission> permissionList=permissionService.list(queryWrapper1);

		model.addAttribute("permissionList",permissionList);
		List<Role> roleList=roleService.list(queryWrapper);
		model.addAttribute("roleList",roleList);
		return "admin/role/index";
	}
	@GetMapping("/toedit")
	public String toedit(Model model,Integer id) {
		Role role=null;
		if(id!=null){
		role=	roleService.getById(id);

		}
		else{
			role=new Role();
		}
		model.addAttribute("role",role);
		return "admin/role/edit";
	}
	@PostMapping("/edit")
	public String edit(@Validated Role role ,BindingResult result) {
		if(result.hasErrors()){
			//model.addAttribute("role",role);
			return "admin/role/edit";
		}
		if(role.getId()!=null){
			roleService.updateById(role);
		}
		else{
			roleService.save(role);
		}

		return "redirect:index";
	}
	@GetMapping("/delete")
	public String delete(@NotNull Integer id) {
		if(id!=null){
			roleService.removeById(id);
		}
		return "redirect:index";
	}
}
